package user

import (
	"github.com/gin-gonic/gin"
	"webProject/handler"
	"webProject/model"
	"webProject/pkg/auth"
	"webProject/pkg/errno"
	"webProject/pkg/token"
)

func Login(c *gin.Context) {
	var u model.UserModel
	if err := c.Bind(&u); err != nil {
		handler.SendResponse(c, errno.ErrBind, nil)
		return
	}

	d, e := model.GetUser(u.Username)
	if e != nil {
		handler.SendResponse(c, errno.ErrUserNotFound, nil)
		return
	}

	if e = auth.Compare(d.Password, u.Password); e != nil {
		handler.SendResponse(c, errno.ErrPasswordIncorrect, nil)
		return
	}

	t, e := token.Sign(c, token.Context{
		ID:       d.Id,
		Username: d.Username,
	}, "")

	if e != nil {
		handler.SendResponse(c, errno.ErrToken, nil)
		return
	}

	handler.SendResponse(c, nil, model.Token{Token: t})

}
